import { View, StyleSheet, TouchableHighlight, Text } from "react-native";
import type { StyleProp, ViewStyle, TextStyle, TouchableHighlightProps, TextProps } from "react-native";
import Btn from "@/components/Btn";
import Dialog, { Props as DialogProps } from "@/components/Dialog";
import theme from "@/styles/theme";
import globalMethods from "@/GlobalMethodProvider";

export type Props = DialogProps & {
  /** 按钮容器 style */
  btnContainerStyles?: StyleProp<ViewStyle>;

  /** 按钮风格 */
  btnStyle?: "small" | "big";

  /** 取消按钮事件 */
  onClose?: () => void;

  /** 取消按钮文本 */
  closeBtnText?: string;

  /** 隐藏取消按钮 */
  hideCloseBtn?: boolean;

  /** 确定按钮事件 */
  onConfirm?: () => void;

  /** 确定按钮文本 */
  confirmBtnText?: string;

  /** 隐藏确定按钮 */
  hideConfirmBtn?: boolean;

  /** 内容位置:  */
  contentPosition?: "right" | "center" | "left";

  /** 底部按钮位置, `small` 才有效 */
  smallBtnPosition?: "right" | "center" | "left";

  /** 底部按钮之前插槽, `small` 才有效 */
  dialogViewBeforeBtn?: (...args: any) => JSX.Element | null;

  /** 底部按钮之后插槽, `small` 才有效 */
  dialogViewAfterBtn?: (...args: any) => JSX.Element | null;

  /** 显示中间按钮, `big` 才有效 */
  showMiddleBtn?: boolean;

  /** 中间按钮文本, `big` 才有效 */
  middleBtnText?: string;

  /** 点击中间按钮事件, `big` 才有效 */
  onMiddle?: () => void | Error;

  /** 多个按钮, `big` 才有效 */
  bigBtnList?: () => BigBtnType[];
  /**
   * 多个按钮的位置: `big` 才有效(默认: left)
   * - left: 最左边
   * - middle: 取消和确定按钮的中间
   * - right: 最右边
   */
  bigBtnListPosition?: "left" | "middle" | "right";
};

/** Big 风格按钮 */
export type BigBtnType = {
  /** 按钮文本 */
  text: string | (() => JSX.Element);
  /** 点击事件 */
  onClick?: () => void | Error;
  /** 按钮容器 style */
  containerStyle?: StyleProp<ViewStyle>;
  /** 按钮文本 style */
  textStyle?: StyleProp<TextStyle>;
  /** TouchableHighlightProps */
  TouchableHighlightProps?: TouchableHighlightProps;
  /** TouchableHighlightProps */
  TextProps?: TextProps;
};

/** 模态框 */
const ModalBox = (props: Props) => {
  const isSmall = props.btnStyle === "small";
  const smallBtnPosition = props.smallBtnPosition;
  const contentPosition = props.contentPosition;

  /** 中间按钮回调 */
  const onMiddle = () => {
    const res = props?.onMiddle?.();
    if (!(res instanceof Error)) {
      globalMethods.$hideModalBox();
    }
  };

  /** 处理 BigBtn 点击事件 */
  const handleBigBtnClick = (item: BigBtnType) => {
    return () => {
      const res = item.onClick?.();
      if (!(res instanceof Error)) {
        globalMethods.$hideModalBox();
      }
    };
  };

  /** 构建 middle 按钮 */
  const buildBigBtn = (list: BigBtnType[]) => {
    return list.map((e, i) => (
      <TouchableHighlight
        key={i}
        onPress={handleBigBtnClick(e)}
        style={[
          styles.baseBtn,
          // 这里要判断 right 时的第一个需要左边框
          i === 0 && bigBtnListPosition === "right" ? styles.leftBorder : null,
          styles.rightBorder,
          e.containerStyle
        ]}
        activeOpacity={0.6}
        underlayColor="#f3f4f6"
        {...e.TouchableHighlightProps}
      >
        <Text lineBreakMode="tail" numberOfLines={1} {...e.TextProps} style={[styles.btnText, e.textStyle]}>
          {typeof e.text === "function" ? e.text() : e.text}
        </Text>
      </TouchableHighlight>
    ));
  };

  const renderBigBtnList = () => props.bigBtnList && buildBigBtn(props.bigBtnList());

  const bigBtnListPosition = props.bigBtnListPosition || "left";
  /** big 按钮按钮 */
  const BtnComp = (
    <View style={[styles.btnContainer, props.btnContainerStyles]}>
      {bigBtnListPosition === "left" && renderBigBtnList()}
      {!props.hideCloseBtn && (
        <TouchableHighlight
          onPress={props.onClose}
          style={[styles.baseBtn, styles.rightBorder]}
          activeOpacity={0.6}
          underlayColor="#f3f4f6"
        >
          <Text style={styles.btnText}>{props.closeBtnText || "取 消"}</Text>
        </TouchableHighlight>
      )}
      {bigBtnListPosition === "middle" && renderBigBtnList()}
      {props.showMiddleBtn && (
        <TouchableHighlight
          onPress={onMiddle}
          style={[styles.baseBtn, styles.rightBorder]}
          activeOpacity={0.6}
          underlayColor="#f3f4f6"
        >
          <Text style={styles.btnText}>{props.middleBtnText || ""}</Text>
        </TouchableHighlight>
      )}
      {!props.hideConfirmBtn && (
        <TouchableHighlight
          onPress={props.onConfirm}
          style={styles.baseBtn}
          activeOpacity={0.6}
          // underlayColor={theme.primary}
          underlayColor="#f3f4f6"
        >
          <Text style={[styles.btnText, { color: theme.primary }]}>{props.confirmBtnText || "确 定"}</Text>
        </TouchableHighlight>
      )}
      {bigBtnListPosition === "right" && renderBigBtnList()}
    </View>
  );

  /** small 风格按钮 */
  const SmallBtnComp = (
    <View
      style={[
        styles.smallBtnContainer,
        {
          justifyContent:
            smallBtnPosition === "left" ? "flex-start" : smallBtnPosition === "center" ? "center" : "flex-end"
        },
        props.btnContainerStyles
      ]}
    >
      {props.dialogViewBeforeBtn && props.dialogViewBeforeBtn()}
      {!props.hideCloseBtn && (
        <Btn
          text={props.closeBtnText || "取 消"}
          type="info"
          onClick={props.onClose}
          containerStyle={{ marginRight: 12 }}
        />
      )}
      {!props.hideConfirmBtn && <Btn text={props.confirmBtnText || "确 定"} type="primary" onClick={props.onConfirm} />}
      {props.dialogViewAfterBtn && props.dialogViewAfterBtn()}
    </View>
  );

  if (isSmall) {
    if (props.bigBtnList) {
      if (__DEV__) {
        console.warn("ModalBox 的按钮风格为 small, 但是指定了 bigBtnList 插槽, 请检查是否设置错误");
      }
    }
  } else {
    if (props.dialogViewBeforeBtn || props.dialogViewAfterBtn) {
      if (__DEV__) {
        console.warn(
          "ModalBox 的按钮风格为 big, 但是指定了 dialogViewBeforeBtn 或 dialogViewAfterBtn 插槽, 请检查是否设置错误"
        );
      }
    }
  }

  return (
    <Dialog
      {...props}
      containerStyle={[{ padding: isSmall ? 10 : 0, borderRadius: 12 }, props.containerStyle]}
      titleContaier={[
        {
          paddingTop: isSmall ? 0 : 5,
          paddingBottom: isSmall ? 0 : 5,
          justifyContent: isSmall ? "flex-start" : "center",
        },
        props.titleContaier
      ]}
      // small 才有左边的图标
      titleIconComponent={isSmall ? props.titleIconComponent : () => null}
      titleTextStyle={[{ fontSize: isSmall ? 18 : 20 }, props.titleTextStyle]}
    >
      <View
        style={[
          styles.contentContainer,
          {
            minHeight: isSmall ? 80 : 110,
            alignItems: contentPosition === "right" ? "flex-end" : contentPosition === "center" ? "center" : "flex-start",
          },
          props.contentContainerStyle
        ]}
      >
        {props.children}
      </View>
      {isSmall ? SmallBtnComp : props.hideCloseBtn && props.hideConfirmBtn && !props.showMiddleBtn ? null : BtnComp}
    </Dialog>
  );
};

const borderColor = "#eaebec";
const styles = StyleSheet.create({
  contentContainer: {
    padding: 20,
    justifyContent: "center"
  },
  btnContainer: {
    flexDirection: "row",
    height: 55,
    backgroundColor: "white",
    borderTopWidth: 0.5,
    borderTopColor: borderColor,
    borderStyle: "solid"
  },
  smallBtnContainer: {
    flexDirection: "row",
    justifyContent: "flex-end"
  },
  baseBtn: {
    alignItems: "center",
    justifyContent: "center",
    flex: 1
  },
  rightBorder: {
    borderRightWidth: 0.5,
    borderRightColor: borderColor,
    borderStyle: "solid"
  },
  leftBorder: {
    borderLeftWidth: 0.5,
    borderLeftColor: borderColor,
    borderStyle: "solid"
  },
  titleContaier: {
    paddingBottom: 0
  },
  btnText: {
    fontSize: 16,
    fontWeight: "bold"
  }
});

export default ModalBox;
